package com.ms.oschina.base;

import android.os.AsyncTask;

import com.ms.oschina.bean.HttpResponse;
import com.ms.oschina.util.UiUtils;


public abstract class BaseAsyncTask<T> extends
		AsyncTask<Void, Void, HttpResponse<T>> {

	private HttpResponse<T> httpResponse;

	// 1.预加载, 运行在主线程
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	// 2.正在加载, 运行在子线程(核心方法), 可以直接异步请求
	@Override
	protected HttpResponse<T> doInBackground(Void... params) {
		httpResponse = new HttpResponse<T>();
		try {
			httpResponse.response = exeCute();
		} catch (Exception e) {
			// 将异常转换成errorcode
			
			
			httpResponse.e = e;
			e.printStackTrace();
		}
		return httpResponse;
	}

	public void setErrorCode(int errorCode) {
		if (httpResponse != null) {
			httpResponse.errorCode = errorCode;
		}
	}

	public void setObject(Object message) {
		httpResponse.obj = message;
	}

	// 4.加载结束, 运行在主线程(核心方法), 可以直接更新UI
	@Override
	protected void onPostExecute(HttpResponse<T> result) {
		onPostExe(result);
		super.onPostExecute(result);
	}

	/**
	 * 子线程中 执行网络工作
	 * 
	 * @return
	 */
	protected abstract T exeCute() throws Exception;

	/**
	 * 加载结束
	 * 
	 * @param result
	 */
	protected abstract void onPostExe(HttpResponse<T> result);

}
